angular.module('starter.sidemenu.controllers', [])

.controller('AppCtrl', function($scope, $state, $ionicModal, $timeout, CategoryListService) {
  CategoryListService.all().then(function(categories) {
    $scope.categories = categories;
  });

  // Form data for the login modal
  $scope.loginData = {username:"default"};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    console.log('Doing login', $scope.loginData);

    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };

  $scope.goCategory = function(categoryId){
    $state.go("app.notelist", {categoryId:categoryId})
  }
})

.controller('PlayListsCtrl', function($scope, $state, PlayListService,
       $ionicGesture, $ionicActionSheet, $ionicNavBarDelegate, $timeout) {
  $timeout( function() {
    $ionicNavBarDelegate.showBackButton(false);
  }, 0);

  PlayListService.all().then(function(playlists) {
    $scope.playlists = playlists;
  });

  $scope.search = function() {
    $state.go('app.search', { });
  }

  // "排序"Event
  var nonePopover = function() {
    for (var i = 1; i <= 10; i++) {
        var p = angular.element(document.querySelector('#nspopover-' + i ));
        p.css('display', 'none');
    }
  }
  $scope.sort = function() {
    nonePopover();
    $ionicActionSheet.show({
      buttons: [
        { text: '按<b>日期</b>排序' },
        { text: '按<b>标题</b>排序' }
      ],
      titleText: '选择排序方法',
      cancelText: '关闭',
      cancel: function() {
        return true;
      },
      buttonClicked: function(index) {
        var sortKey="";
        switch ( index ) {
          case 0: sortKey="date";break;
          case 1: sortKey="title";break;
          default: sortKey="id";
        }
        PlayListService.all(sortKey).then(function(playlists) {
          $scope.playlists = playlists;// 未完成
        });
        return true;
      }
    });
  }
  
  $scope.show = function(playlistId){
    $state.go("app.single", {playlistId: playlistId});
  };

  // 点击Listview中的Checkbox结束当前任务
  $scope.finish = function(todoid, $event) {
    // TODO
    $event.stopPropagation();
  }

  // 长按Listview跳转到任务批量处理页面
  var element = angular.element(document.querySelector('#playlist'));
  $ionicGesture.on("hold", function (event) {
      $state.go('app.playlistsedit', { groupId: $stateParams.groupId });
  }, element);

})

.controller('PlayListCtrl', function($scope, $stateParams, PlayListService) { 
  PlayListService.get($stateParams.playlistId).then(function(playlists) {
    $scope.playlist = playlists[0];
  });
})

.controller('SearchCtrl', function($scope, $stateParams, PlayListService, $ionicNavBarDelegate, $timeout) { 
  // 从向导页面跳转过来的话，不显示返回按钮
  
  $scope.searchKey = "";

　　// "搜索任务"Event
  $scope.searchToDo = function(searchKey) {
      if (searchKey != undefined && searchKey != "")　{
          PlayListService.findByTitle(searchKey).then(function(playlists) {
            $scope.playlists = playlists;
          });
      }
  }
})

.controller('BrowseCtrl', function($scope, $state, $ionicModal) { 
  $scope.colors = ["positive", "calm", 
    "balanced", "energized", "assertive", "royal", "dark"]
  $scope.isStar = false;
  $scope.newTagName="";
  $scope.myTags = [
    {id:1, name:"ionic", className:"royal"},
    {id:2, name:"css", className:"calm"}
  ];
  $scope.currTags = [];
  var maxTagId = $scope.myTags.lenght>0?($scope.myTags.sort(function(a, b){
      return parseInt(a.id) < parseInt(b.id);
  })[0].id):0;

  $scope.toggleStar = function() {
      $scope.isStar = !$scope.isStar;
  };

  $ionicModal.fromTemplateUrl('tags-popover.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal  = modal;
  });
  $scope.openModal = function() {
    $scope.modal.show();
  };  
  $scope.closeModal = function() {
    $scope.modal.hide();
  };

  $scope.addTag = function(){
    var $newTag = angular.element(document.querySelector('#txtTagName'));
    var newTagName = $newTag.val();
    if(newTagName == ""){
      alert("please input new tag name");
      return false;
    }
    var isExists = $scope.myTags.filter(function(item, index){
      return item.name == newTagName;
    }).length>0;
    if(isExists){
      alert("This tag has exists");
      return false;
    }

    var tag = {id:maxTagId++, name:newTagName, className:$scope.colors[maxTagId%($scope.colors.length)] };
    $scope.myTags.push(tag);
    $newTag.val("");
  };

  $scope.removeTag = function(item){
    $scope.myTags.splice($scope.myTags.indexOf(item), 1);
  };

  $scope.moveTag = function(item, isAdd){
    if(isAdd){
      $scope.currTags.push(item);
      $scope.myTags.splice($scope.myTags.indexOf(item), 1);
    }
    else{
      $scope.myTags.push(item);
      $scope.currTags.splice($scope.currTags.indexOf(item), 1);
    }
  };

  $scope.cancel = function(){
    $state.go('app.playlists');
  };

})


.controller('NoteListCtrl', function($scope, $state, $stateParams,
       CategoryListService, NoteListService, 
       $ionicNavBarDelegate, $timeout, $ionicGesture, $ionicActionSheet) {
  $timeout(function() {
    $ionicNavBarDelegate.showBackButton(false);
  }, 0);

  var categoryId = $stateParams.categoryId;
  var getNoteList = function(sortKey){
    var categoryIds = 0;
    if(categoryId!="" && categoryId!=0){
      categoryIds = [categoryId];
    }

    NoteListService.getToCategory(categoryIds, sortKey).then(function(Categories) {
      $scope.currCategories = Categories;

      $timeout(function() {
        var noteItemList = document.querySelectorAll('.item-list');      
        var element = angular.element(noteItemList);
        $ionicGesture.on("hold", function (event) {
          $scope.doDelete = true;  
          try{$scope.$apply();}catch(ex){}
          //显示checkbox以后点击item不会触发click事件了
        }, element);
      }, 2000);  
    });
  };
  getNoteList();

  $scope.showNote = function(noteId){
    $state.go("app.single", {noteId: noteId});
  };

  // 点击Listview中的Checkbox结束当前任务
  $scope.finish = function(todoid, $event) {
    // TODO
    $event.stopPropagation();
  }

  $scope.isSelectAll = true;
  $scope.toggleSelect = function(isSelectAll){
    angular.forEach($scope.currCategories, function(item, index){  
      angular.forEach(item.notelist, function(node, i){  
        node.selected = isSelectAll;        
      });
    });
    $scope.isSelectAll = !isSelectAll;
  };

  $scope.deleteNotes = function(){
    alert("deleteNotes");
  };

  $scope.cancelDelete = function(){
    $scope.doDelete = false;
  };

  $scope.addNote =function(){
    $state.go("app.browse");
  };

  $scope.searchNote = function() {
    $state.go('app.search', { });
  };

  // "排序"Event
  var nonePopover = function() {
    for (var i = 1; i <= 10; i++) {
        var p = angular.element(document.querySelector('#nspopover-' + i ));
        p.css('display', 'none');
    }
  }
  $scope.sort = function() {
    nonePopover();
    $ionicActionSheet.show({
      buttons: [
        { text: '按<b>日期</b>排序' },
        { text: '按<b>标题</b>排序' }
      ],
      titleText: '选择排序方法',
      cancelText: '关闭',
      cancel: function() {
        return true;
      },
      buttonClicked: function(index) {
        var sortKey="";
        switch ( index ) {
          case 0: sortKey="date";break;
          case 1: sortKey="title";break;
          default: sortKey="id";
        }
        /*
        PlayListService.all(sortKey).then(function(playlists) {
          $scope.playlists = playlists;// 未完成
        });*/
        getNoteList(sortKey);
        return true;
      }
    });
  };


})

;
